package com.snailhd.service.impl;

import com.snailhd.common.entity.IResult;
import com.snailhd.common.entity.SubMsgResult;
import com.snailhd.crawler.DownloadHistoryCsvAndParseToDBExector;
import com.snailhd.entity.Stock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author hd
 * @date 2019-12-10 09:43
 */

@Slf4j
@Component
public class MultiThreadDownloadStockdayHistoryHandler {


    /**
     * 是否正在下载中
     */
    private boolean downloading;

    @Resource
    DownloadHistoryCsvAndParseToDBExector downloadExector;

    private ExecutorService executor = Executors.newFixedThreadPool(4);


    private CountDownLatch countDownLatch;

    public IResult download(List<Stock> list, String beginDate, String endDate) throws Exception{
        if(downloading){
            return new IResult().setSubMsg(new SubMsgResult("DOWNLOADING","正在下载中"));
        }

        try {
            downloading = true;

            countDownLatch = new CountDownLatch(list.size());

            list.forEach(e->{
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String code = e.getCode();
                            if(e.getSymbol().startsWith("sz")){
                                code = "1"+code;
                            }else if(e.getSymbol().startsWith("sh")){
                                code = "0"+code;
                            }
                            downloadExector.exec(code,false,beginDate,endDate);
                        } catch (Exception ex) {
                            log.error("下载异常{}",e,ex);
                        } finally {
                            countDownLatch.countDown();
                            log.info("------>count:{}",countDownLatch.getCount());
                        }
                    }
                });
            });
            countDownLatch.await();
            executor.shutdown();
        } finally {
            downloading = false;
        }

        return new IResult();

    }
}
